package com.hourses.service.impl;

import com.hourses.mapper.InStoreMapper;
import com.hourses.mapper.PurchaseMapper;
import com.hourses.page.Page;
import com.hourses.pojo.InStore;
import com.hourses.pojo.Purchase;
import com.hourses.pojo.Result;
import com.hourses.service.PurchaseService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description:
 * @Author:LiTao
 * @Date:2025/5/8 13:14
 */
@Service
public class PurchaseServiceImpl implements PurchaseService {
    //向buy_list表中插入数据
    @Autowired
    private PurchaseMapper purchaseMapper;
    @Override
    public Result addBuyList(Purchase purchase) {
        Integer count = purchaseMapper.addBuyList(purchase);
        if (count>0){
            return Result.ok("添加成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"添加失败！请联系管理员...");
    }

    //查询采购列表
    @Override
    public Result selectBuyList(Purchase purchase, Page page) {
        //step1:先查询满足查询条件的采购单有多少
        Integer count = purchaseMapper.selectPurchasesCount(purchase);
        page.setTotalNum(count);
        //step2:查询当前页需要展示的采购列表
        List<Purchase> purchases = purchaseMapper.selectPurchases(purchase, page);
        page.setResultList(purchases);
        return Result.ok(page);
    }

    //删除采购单
    @Override
    public Result deleteBuyList(Integer buyId) {
        Integer count = purchaseMapper.deleteBuyList(buyId);
        if (count>0){
            return Result.ok("删除成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"删除失败！请联系管理员...");
    }

    //修改采购单
    @Override
    public Result updateBuyList(Purchase purchase) {
        Integer count = purchaseMapper.updateBuyList(purchase);
        if (count>0){
            return Result.ok("修改成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"修改失败！请联系管理员...");
    }

    //生成入库单    http://localhost:3000/api/purchase/in-warehouse-record-add    POST
    //有两步操作：
    //step1:向in_store表中添加数据,添加成功以后，再执行下面的操作
    //step2:修改buyList表中的is_in字段为1,并且更新fact_buy_num字段

    @Autowired
    private InStoreMapper inStoreMapper;

    @Override
    @Transactional    //添加事务
    public Result createInStoreData(InStore inStore) {
        Integer count = inStoreMapper.insertInStore(inStore);
        if (count>0){
            //插入数据成功,修改buyList表中的IsIn字段为1
            Integer count1 = purchaseMapper.updateIsIn(inStore.getBuyId());
            if (count1>0){
                //修改成功
                return Result.ok("生成入库单成功！");
            }
            return Result.err(Result.CODE_ERR_BUSINESS,"生成入库单失败！请联系管理员...");
        }
        //插入数据失败
        return Result.err(Result.CODE_ERR_BUSINESS,"生成入库单失败！请联系管理员...");
    }
}
